package com.yb.mini.gateway.custom;

import lombok.Getter;
import lombok.Setter;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.cloud.gateway.support.HttpStatusHolder;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;

import java.net.URI;
import java.util.Arrays;
import java.util.List;

/**
 * 命名方式仿照内置的即可,例如PrefixPathGatewayFilterFactory
 * 注意需要加入Spring容器
 *
 * @author yangbiao
 * @date: 2024/03/14
 */
@Component
public class AppRedirectUriGatewayFilterFactory extends AbstractGatewayFilterFactory<AppRedirectUriGatewayFilterFactory.Config> {

    public AppRedirectUriGatewayFilterFactory() {
        super(AppRedirectUriGatewayFilterFactory.Config.class);
    }

    @Override
    public GatewayFilter apply(AppRedirectUriGatewayFilterFactory.Config config) {
        return (exchange, chain) -> {
            if (!exchange.getResponse().isCommitted()) {
                final String redirectUri = config.getRedirectUri();
                URI uri = URI.create(redirectUri);
                final HttpStatus httpStatus = HttpStatus.FOUND;
                final HttpStatusHolder httpStatusHolder = new HttpStatusHolder(httpStatus, httpStatus.value());
                ServerWebExchangeUtils.setResponseStatus(exchange, httpStatusHolder);
                ServerHttpResponse response = exchange.getResponse();
                response.getHeaders().set("Location", uri.toString());
                return response.setComplete();
            }
            return chain.filter(exchange);
        };

    }

    @Getter
    @Setter
    public static class Config {
        private String redirectUri;
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("redirectUri");
    }

}
